//
//  HEPhotosContainerView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/22.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEPhotosContainerView.h"
#import "KNPhotoBrowser.h"

@interface HEPhotosContainerView()<KNPhotoBrowserDelegate>

@property (nonatomic, strong) NSMutableArray *itemsArr;
@property (nonatomic, strong) KNPhotoBrowser *photoBrowser;
@end

@implementation HEPhotosContainerView

- (NSMutableArray *)itemsArr{
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}

- (instancetype)initWithMaxItemsCount:(NSInteger)count {
    if (self = [super init]) {
        self.maxItemsCount = count;
    }
    return self;
}

- (void)setupSubViews {
    
//    NSArray *urlArr = @[@"http://ww2.sinaimg.cn/thumbnail/677febf5gw1erma104rhyj20k03dz16y.jpg",
//    @"http://ww3.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr1xydcj20gy0o9q6s.jpg",
//    @"http://ww2.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr39ht9j20gy0o6q74.jpg",
//    @"http://ww3.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr3xvtlj20gy0obadv.jpg",
//    @"http://ww2.sinaimg.cn/bmiddle/642beb18gw1ep3629gfm0g206o050b2a.gif"
//    ];


}

- (void)setPhotoNamesArray:(NSArray *)photoNamesArray {
    
    _photoNamesArray = photoNamesArray;
    [self.itemsArr removeAllObjects];
        
    // 创建items
    NSMutableArray *items2 = [NSMutableArray array];

    for (int i = 0; i < photoNamesArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView setUserInteractionEnabled:YES];
        [imageView setBackgroundColor:[UIColor grayColor]];
        [imageView setContentMode:UIViewContentModeTop | UIViewContentModeLeft | UIViewContentModeRight];
        [imageView setTag:i];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:photoNamesArray[i]] placeholderImage:IMAGE_NAMED(@"noImage")];
        [items2 addObject:imageView];
        [self addSubview:imageView];
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigImage:)];
        imageView.userInteractionEnabled=YES;
        [imageView addGestureRecognizer:tapGes];
        
        KNPhotoItems *items = [[KNPhotoItems alloc] init];
          items.url = photoNamesArray[i] ;
          items.sourceView = imageView;
          [self.itemsArr addObject:items];
    }
    
    //
    [items2 mas_distributeSudokuViewsWithFixedLineSpacing:10 fixedInteritemSpacing:10 warpCount:3 topSpacing:10 bottomSpacing:10 leadSpacing:0 tailSpacing:0];
}

- (void)bigImage:(UITapGestureRecognizer *)tap {
 
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    photoBrowser.currentIndex = tap.view.tag;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}



/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
    
    __weak typeof(self) weakself = self;
    KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
 
            [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
        }
    }];
    
    [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [photoBrowser setImmediatelyPlayerRate:2];
    }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
        [photoBrowser setImmediatelyPlayerRate:1];
    }
}


- (void)toSaveImage:(NSURL *)url {
 
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    if ([manager cacheKeyForURL:url]) {
       [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
           // 保存图片到相册中
           UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];
        return;
    }
    else {
        //从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];
        // 保存图片到相册中
        UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}
//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [Dialog toast:@"图片保存失败" delay:2.0];
    }
    else  // No errors
    {
        [Dialog toast:@"图片保存成功" delay:2.0];
    }
}

@end
